package com.carboy.launch;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Application;
import android.app.ActivityManager.RunningServiceInfo;
import android.bluetooth.BluetoothAdapter;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetFileDescriptor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap.Config;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.UEventObserver.UEvent;
import android.os.Message;
import android.os.UEventObserver;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.carboy.launch.db.DbHelper;
import com.carboy.launch.utils.AdbUtil;
import com.carboy.launch.utils.JwdLog;
import com.carboy.launch.utils.Tool;
import com.carengine.service.CvrService;
import com.iflytek.cloud.SpeechUtility;
import com.jwd.clouddog.tools.JwdServerDateMethod;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import android.os.SystemProperties;
import android.provider.Settings;

/**
 * 一般建议在自定义 Application 类里初始化。也可以在主 Activity 里。
 */
public class BaseApplication extends Application {
	private static final String TAG = "JK_LauncherCar2_BaseApplication";
	public static boolean isNetworkConnected = false;
	public static int netWorkType = -1;
	public static boolean updating_flag = false;
	private Context mContext;
	private static ArrayList<Activity> mActivitys;
	public static MediaPlayer mp;
	public final static String LAUNCHER_CREATE = "com.huixin.carnav.activity.column.ColumnMainActivity.openService";
	private Timer mTimer;
	private static BaseApplication instance;
	private WifiManager wifiManager; // wifi连接管理类
	private DbHelper dbHelper;
	private SQLiteDatabase db;
	
	private static final String SERVICE_NAME = "com.rk.carrecorder.CameraCrashService";

    private ActivityManager mManager;
    private AudioManager mAudioManager;
    private ArrayList<RunningServiceInfo> mRunningServiceInfo; 
    private WindowManager.LayoutParams windowParams = new WindowManager.LayoutParams();
    private boolean mBootStart;
    private BluetoothAdapter mBluetoothAdapter;
    private static final int WAIT_FOR_ACC_ON = 13;
    private static final int WAIT_FOR_REVERSE_ON = 14;
    private static final int WAIT_FOR_REVERSE_OVER = 15;
    private byte[] mLock = new byte[0];
    PowerManager mPowerManager;
    PowerManager.WakeLock mWakeLock;
	
	private Handler mHandler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message arg0) {
			switch (arg0.what) {
			case 1:
				JwdServerDateMethod.bindCloudService(BaseApplication.this);
				break;

			default:
				break;
			}
			return false;
		}
	});

	@Override
	public void onCreate() {
		super.onCreate();
		mContext = this;
		instance = this;
		mActivitys = new ArrayList<Activity>();
		// --------------------初始化------------------------
		// 是否检测调试模式
		AdbUtil.setCheckAdb(false);
		// 是否开启Log打印及语音播报测试！！！！//正式版本均设置为false
		JwdLog.setLog(false);
		JwdLog.setPlayVoice(false);
		JwdLog.setToast(false);
		try {
		    JwdServerDateMethod.bindCloudService(BaseApplication.this);
		} catch(Exception e) {
			Log.e(TAG, "can't connect to carboy clound");
		    e.printStackTrace();
		}
		// 发送启动广播
		Intent intent = new Intent(LAUNCHER_CREATE);
		intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
		sendBroadcast(intent);
        sendBroadcast(new Intent("android.intent.action.RKCARRECORDER.ON_STOP"));
		// 图片缓存
		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.loading_image_hint) // 设置图片在下载期间显示的图片
				.showImageForEmptyUri(R.drawable.loading_image_hint) // 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.loading_image_hint) // 设置图片加载/解码过程中错误时候显示的图片
				.imageScaleType(ImageScaleType.EXACTLY) // 设置图片缩放
				.bitmapConfig(Config.RGB_565) // 图片解码类型
				.cacheInMemory(true)// 是否保存到内存
				.cacheOnDisc(true).build();// 是否保存到sd卡上（硬盘控件）
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this)
				.defaultDisplayImageOptions(defaultOptions)
				.threadPoolSize(3)
				// 线程池内加载的数量
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new UsingFreqLimitedMemoryCache(1024 * 1024))
				// 通过自己的内存缓存实现
				.memoryCacheSize(1024 * 1024).discCacheSize(1024 * 1024)
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.discCacheFileCount(50)
				// 缓存的文件数量
				.memoryCache(new WeakMemoryCache())
				.tasksProcessingOrder(QueueProcessingType.LIFO).build();
		ImageLoader.getInstance().init(config);

		SpeechUtility.createUtility(BaseApplication.this, "appid="
				+ getString(R.string.app_id));
		startTimer();
		
		startCvrService();
//		whetherBootStart();
        mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock= mPowerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeUp");

//		whetherStartActivity();
		deleteLostDir();
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		mManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		//mUEventObserver.startObserving("GPIO_NAME=car-acc GPIO_STATE=on");
		//mUEventObserver.startObserving("GPIO_NAME=car-acc GPIO_STATE=over");
		
		//mUEventObserver.startObserving("GPIO_NAME=car-reverse GPIO_STATE=on");
		//mUEventObserver.startObserving("GPIO_NAME=car-reverse GPIO_STATE=over");
		sendBroadcast(new Intent("android.intent.action.LAUNCHER_STARTED"));
	}

    private void startCvrService() {
        Intent service = new Intent();
        service.setClass(this, CvrService.class);
        startService(service);
    }

    private void whetherBootStart() {
        try {
            Context otherAppsContext = createPackageContext(
                    "com.rk.carrecorder", Context.CONTEXT_IGNORE_SECURITY);
            SharedPreferences settings = otherAppsContext.getSharedPreferences(
                    "com.rk.carrecorder_preferences_camera",
                    Context.MODE_MULTI_PROCESS);
            mBootStart = settings.getBoolean("pref_boot_start", true);
        } catch (NameNotFoundException e1) {
            e1.printStackTrace();
        }
    }

    private static final boolean BOOT_RECORD_BG = true;
    private void whetherStartActivity() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mBootStart && !isServiceWorked(SERVICE_NAME)) {
                    String status = SystemProperties
                            .get("boot.car.reverse", "0");
                    while (status.equals("1")) {
                        status = SystemProperties.get("boot.car.reverse", "0");
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (SystemProperties.get("sys.car.reverse", "0").equals(2)) {
                        return;
                    }
                    try {
                        SystemProperties.set("sys.car.reverse", "2");
                        Thread.sleep(6000);
                        if(BOOT_RECORD_BG) {
                            Intent intent = new Intent();
                            ComponentName com = new ComponentName("com.rk.carrecorder",
                                    "com.rk.carrecorder.CameraActivity");
                            intent.setComponent(com);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("BOOTUP", true);
                            startActivity(intent);
                        } else {
                            Intent sIntent = new Intent();
                            ComponentName sCom = new ComponentName("com.rk.carrecorder",
                                    "com.rk.carrecorder.CameraCrashService");
                            sIntent.setComponent(sCom);
                            sIntent.putExtra("record_bg", true);
                            startService(sIntent);
                        }
                    } catch (ActivityNotFoundException e) {
                        Log.e(TAG, "occur activity not found exception");
                    } catch (Exception e) {
                        Log.e(TAG, "occur exception");
                    }
                }
            }
        }).start();
    }

    private boolean isServiceWorked(String serviceName) {
        mRunningServiceInfo = (ArrayList<RunningServiceInfo>) mManager.getRunningServices(Integer.MAX_VALUE);
        for(RunningServiceInfo info : mRunningServiceInfo)  {
            if(info.service.getClassName().toString().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

	/***
	 * 开启一个计时器
	 */
	private void startTimer() {
		mTimer = new Timer(true);
		MyTimerTask timerTask = new MyTimerTask();
		mTimer.schedule(timerTask, 0, 30 * 60 * 1000);
		// Toast.makeText(mContext, "开始计时", 3000).show();
	};

	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
	}

	/**
	 * 创建全局变量 全局变量一般都比较倾向于创建一个单独的数据类文件，并使用static静态变量
	 * 这里使用了在Application中添加数据的方法实现全局变量
	 */
	private WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();

	public WindowManager.LayoutParams getMywmParams() {
		return wmParams;
	}

	/** 检测网络连接状态 */
	public boolean checkNetwork() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null)
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED)
						return true;
				}
		}
		return false;
	}

	public static void playClickVoice(Context context) {
		if (true) {
			try {
				if (mp == null) {
					mp = new MediaPlayer();
				}
				mp.reset();
				AssetFileDescriptor afd = context.getResources()
						.openRawResourceFd(R.raw.button_click_voice);
				if (afd == null)
					return;
				mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
						afd.getLength());
				afd.close();

				mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mp.prepare();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			mp.start();
		}
	}

	/**
	 * 获取系统是否安装某个app
	 */
	public boolean isInstall(String pName) {
		boolean iscontains = false;
		PackageManager pManager = this.getPackageManager();
		// 获取手机内所有应用
		List<PackageInfo> packlist = pManager.getInstalledPackages(0);
		for (int i = 0; i < packlist.size(); i++) {
			PackageInfo pak = (PackageInfo) packlist.get(i);

			if (pak.packageName.equals(pName)) {
				iscontains = true;
				return iscontains;
			}
		}

		return iscontains;

	}

	/***
	 * 判断应用是否在最上层
	 * 
	 * @param mContext
	 * @param appName
	 * @return
	 */
	public static boolean isTopActivity(Context mContext, String appName) {
		boolean isTop = false;
		ActivityManager am = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		if (cn.getClassName().contains(appName)) {
			isTop = true;
		}
		return isTop;
	}

	class MyTimerTask extends TimerTask {

		@Override
		public void run() {

			boolean istopVoice = isTopActivity(mContext,
					"com.jwd.jwdvoicetool.JwdVoiceActivity");
			boolean istopCloud = isTopActivity(mContext,
					"com.jwd.clouddog.show.MainPage");
			if (!istopVoice && !istopCloud) {
				Tool.forceCloseApp(mContext, "com.jwd.jwdvoicetool");
				// 发送启动广播

				handler.sendEmptyMessage(0);
			}
			handler.sendEmptyMessage(1);
		}

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			// Toast.makeText(mContext, "清理后台程序", 3000).show();
			switch (msg.what) {
			case 0:
				// Toast.makeText(mContext, "杀死语音进程", 3000).show();
				Intent intent = new Intent(LAUNCHER_CREATE);
				intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
				sendBroadcast(intent);
				break;
			case 1:
				// guanbishezhi
				try {
					if (!isTopActivity(mContext, "com.android.settings")) {
						// Toast.makeText(mContext, "杀死设置进程", 3000).show();
						Tool.forceCloseApp(mContext, "com.android.settings");
					}

					if (!isTopActivity(mContext, "com.android.browser")) {
						// Toast.makeText(mContext, "杀死浏览器进程", 3000).show();
						Tool.forceCloseApp(mContext, "com.android.browser");
					}
					if (!isTopActivity(mContext, "com.qihoo.browser")) {
						// Toast.makeText(mContext, "杀死浏览器进程", 3000).show();
						Tool.forceCloseApp(mContext, "com.qihoo.browser");
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 12:
                synchronized (mLock) {
                    if(mPowerOffTime > 1) {
                        mPowerOffTime--;
                        if (dialog != null && dialog.isShowing()) {
                            dialog.setMessage(getResources().getString(R.string.time_to_power_off, mPowerOffTime));
                            handler.sendEmptyMessageDelayed(12, 1000);
                        }
                    } else {
                        handler.removeMessages(12);
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        if (isServiceWorked(SERVICE_NAME)) {
                            sendBroadcast(new Intent("android.intent.action.ACC_OVER"));
                        } else {
                            standy();
                        }
                    }
                    break;
                }
			case 11:
				dialog();
				break;
			case WAIT_FOR_ACC_ON:
			    ueventAccOn();
			    break;
			case WAIT_FOR_REVERSE_ON:
			    carReverse("on");
			    break;
			case WAIT_FOR_REVERSE_OVER:
			    carReverse("over");
			    break;
			default:
				break;
			}

		};
	};

	public static BaseApplication getInstance() {
		return instance;
	}

	/** 获取数据库对象 */
	private DbHelper getDbHelper() {
		if (dbHelper == null)
			dbHelper = new DbHelper(getApplicationContext());
		return dbHelper;
	}

	/** 获取数据库编辑对象 */
	public SQLiteDatabase getDb() {
		// if (db == null)
		db = getDbHelper().getWritableDatabase();
		return db;
	}

    private long mTimeOfReverse = 0;
    private final UEventObserver mUEventObserver = new UEventObserver() {
        @Override
        public void onUEvent(UEvent event) {
            String state = getState(event.toString(), "GPIO_STATE");
            Log.d(TAG, "CAR ACC OR REVERSE UEventObserver responsed:" + event.toString());
            if(state.equals("on")) {
                if(event.toString().contains("car-acc")) {
                    synchronized (mLock) {
                        if (dialog != null) {
                            if (dialog.isShowing()) {
                                Log.d(TAG, "dialog is showing");
                                dialog.dismiss();
                                handler.removeMessages(12);
                                return;
                            } else {
                                Log.d(TAG, "dialog is not showing");
                            }
                        }
                    }
                    ueventAccOn();
                } else if(event.toString().contains("car-reverse")) {
                    if (SystemClock.uptimeMillis() - mTimeOfReverse < 1000) {
                        Log.d(TAG, "car reverse event to fase,ignore this");
                        mTimeOfReverse = SystemClock.uptimeMillis();
                        handler.removeMessages(WAIT_FOR_REVERSE_ON);
                        handler.removeMessages(WAIT_FOR_REVERSE_OVER);
                        handler.sendEmptyMessageDelayed(WAIT_FOR_REVERSE_ON, 2000);
                        return;
                    }
                    carReverse("on");
                }
            } else if(state.equals("over")){
                if(event.toString().contains("car-acc")) {
                    handler.removeMessages(WAIT_FOR_ACC_ON);    //cancel acc on message
                    handler.sendEmptyMessage(11);
                } else if(event.toString().contains("car-reverse")) {
                    if (SystemClock.uptimeMillis() - mTimeOfReverse < 1000) {
                        mTimeOfReverse = SystemClock.uptimeMillis();
                        handler.removeMessages(WAIT_FOR_REVERSE_ON);
                        handler.removeMessages(WAIT_FOR_REVERSE_OVER);
                        handler.sendEmptyMessageDelayed(WAIT_FOR_REVERSE_OVER, 2000);
                        return;
                    }
                    carReverse("over");
                }
            }
        }
    };

    private void ueventAccOn() {
        accOn();
        mWakeLock.acquire(2000);
        Intent mIntent = new Intent();
        ComponentName comp = new ComponentName("com.rk.carrecorder", "com.rk.carrecorder.CameraActivity");
        mIntent.setComponent(comp);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mIntent.putExtra("BOOTUP", true);
        try {
            startActivity(mIntent);
        } catch(ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    private String getState(String strs, String name) {
        char[] strArr = strs.toCharArray();
        String result = "";
        if(strs.contains(name)) {
            for(int index=strs.indexOf(name) + name.length(); strArr[index] !=','; index++) {
                if(strArr[index] != '=') {
                    result += strArr[index];
                }
            }
        }
        return result.replace(" ", "");
    }

    private AlertDialog dialog;
    private long mPowerOffTime = 15;

    private void dialog() {
        mPowerOffTime = 15;
        dialog = new AlertDialog.Builder(this)
                .setMessage(getResources().getString(R.string.time_to_power_off,mPowerOffTime))
                .setPositiveButton(getResources().getString(R.string.acc_off_poweroff), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        poweroff();
                    }
                }).setNegativeButton(getResources().getString(R.string.acc_off_standby), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        handler.removeMessages(12);
                        if (isServiceWorked(SERVICE_NAME)) {
                            sendBroadcast(new Intent("android.intent.action.ACC_OVER"));
                        } else {
                            standy();
                        }
                    }
                }).create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.setCancelable(false);
        dialog.show();
        handler.sendEmptyMessageDelayed(12, 1000);
    }

    public void standy() {
        accOff();
        gotoSleep();
    }

    private void poweroff() {
        Intent shutdownIntent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
        shutdownIntent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
        shutdownIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(shutdownIntent);
    }

    private void gotoSleep() {
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        pm.goToSleep(SystemClock.uptimeMillis());
    }

    private void accOn() {
//        if(!getMode().equals(USB_MODE_HOST)) {
        Log.d(TAG, getMode());
//        if (mBtWasClosed) {
            openBT();
//        }
//        if (mGpsWasClosed) {
            openGps();
//        }
        if(true) {
            try {
                setMode(USB_MODE_HOST);
                Thread.sleep(2*1000);
            } catch (Exception e) {
                Log.e(TAG, "setMode(" + USB_MODE_HOST + ") fail");
                int x = 10/0;
            }
        } else {
            Log.d(TAG, "it is already " + USB_MODE_HOST);
        }
        Intent mIntent = new Intent();
        mIntent.setAction("com.cayboy.action.ACC_ON");
        mContext.sendBroadcast(mIntent);
    }

    private void accOff() {
//        killAppByPackage("com.rk.carrecorder");
        if (isBtOn()) {
            closeBT();
            mBtWasClosed = true;
        }
        if (isGpsOn()) {
            closeGps();
            mGpsWasClosed = true;
        }
        Intent mIntent = new Intent();
        mIntent.setAction("com.cayboy.action.ACC_OFF");
        mContext.sendBroadcast(mIntent);
//        if(!getMode().equals(USB_MODE_DEVICE)) {
        Log.d(TAG, getMode());
        if(true) {
            try {
                setMode(USB_MODE_DEVICE);
                Thread.sleep(2 * 1000);
            } catch (Exception e) {
                Log.e(TAG, "setMode(" + USB_MODE_DEVICE + ") fail");
                int x = 10/0;
            }
        } else {
            Log.d(TAG, "it is already " + USB_MODE_DEVICE);
        }
    }

    private boolean mBtWasClosed = false;
    private boolean isBtOn() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return mBluetoothAdapter.isEnabled();
    }
    private boolean enableBT(int state) {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(state == 1) {
            if(!mBluetoothAdapter.isEnabled()) {
                return mBluetoothAdapter.enable();
            }
        } else {
            if(mBluetoothAdapter.isEnabled()) {
                return mBluetoothAdapter.disable();
            }
        }
        return true;
    }

    public boolean openBT() {
        return enableBT(1);
    }

    public boolean closeBT() {
        return enableBT(-1);
    }

    private boolean mGpsWasClosed = false;
    public boolean isGpsOn() {
        int mode = Settings.Secure.getInt(mContext.getContentResolver(),
                Settings.Secure.LOCATION_MODE,
                Settings.Secure.LOCATION_MODE_OFF);
        if (mode == android.provider.Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * close gps
     */
    private static final String MODE_CHANGING_ACTION = "com.android.settings.location.MODE_CHANGING";
    private static final String NEW_MODE_KEY = "NEW_MODE";
    public void closeGps() {
        int mode = android.provider.Settings.Secure.LOCATION_MODE_OFF;
        Intent intent = new Intent(MODE_CHANGING_ACTION);
        intent.putExtra(NEW_MODE_KEY, mode);
        mContext.sendBroadcast(intent,
                android.Manifest.permission.WRITE_SECURE_SETTINGS);
        Settings.Secure.putInt(mContext.getContentResolver(),
                Settings.Secure.LOCATION_MODE, mode);
    }
    
    /**
     * open gps
     */
    public void openGps() {
        int mode = android.provider.Settings.Secure.LOCATION_MODE_HIGH_ACCURACY;
        Intent intent = new Intent(MODE_CHANGING_ACTION);
        intent.putExtra(NEW_MODE_KEY, mode);
        mContext.sendBroadcast(intent,
                android.Manifest.permission.WRITE_SECURE_SETTINGS);
        Settings.Secure.putInt(mContext.getContentResolver(),
                Settings.Secure.LOCATION_MODE, mode);
    }


    private void killAppByPackage(String packageName) {
        Log.v(TAG, "require close " + packageName);
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        try {
            activityManager.forceStopPackage(packageName);
        } catch(Exception e) {
            Log.e(TAG, "close " + packageName + " error");
            e.printStackTrace();
        }
    }

    private static final String USB_MODE_PATH = "/sys/kernel/debug/intel_otg/mode";
    private static final String USB_MODE_HOST = "host";
    private static final String USB_MODE_DEVICE = "none";
    //set usb mode(write node)
    private void setMode(String mode){
        Log.i(TAG, "----setMode----" + mode);
        try {
            FileWriter modeWriter = new FileWriter(USB_MODE_PATH, false);
            modeWriter.write(mode);
            modeWriter.flush();
            modeWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //get usb mode(read node)
    private String getMode(){
        Log.i(TAG, "----getMode()----");
        String path = USB_MODE_PATH;
        String result = "";
        try {
            FileReader fread = new FileReader(path);
            BufferedReader buffer = new BufferedReader(fread);
            String str = null;
            while ((str = buffer.readLine()) != null) {
                result = str;
                break;
            }
            buffer.close();
            fread.close();
        }
        catch (IOException e) {
            Log.e(TAG, "IO Exception");
            e.printStackTrace();
            result = getMode();
        }
        Log.d(TAG, "current mode is :" + result);
        return result;
    }

    public String getRunningActivityName() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity = activityManager.getRunningTasks(1).get(0).topActivity
                .getClassName();
        return runningActivity;
    }

    private void deleteLostDir() {
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                try {
                    File file = new File("/mnt/external_sdio/LOST.DIR");
                    if (file.exists() && file.isDirectory()) {
                        file.delete();
                    }
                } catch (Exception e) {
                    
                }
            }
        }).start();
    }

    private void carReverse(String state) {
        handler.removeMessages(WAIT_FOR_REVERSE_ON);
        handler.removeMessages(WAIT_FOR_REVERSE_OVER);
        mTimeOfReverse = SystemClock.uptimeMillis();
        if (state.equals("on")) {
            String status = SystemProperties
                    .get("boot.car.reverse", "0");
            if(status.equals("1")) {
                Log.d(TAG, "camera it is using,return");
                return;
            }
            SystemProperties.set("sys.car.reverse", "2");
            Intent mIntent = new Intent();
            ComponentName comp = new ComponentName("com.rk.carrecorder", "com.rk.carrecorder.CameraActivity");
            mIntent.setComponent(comp);
            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("CAR-REVERSE", "on");
            //mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
            try {
                if(getRunningActivityName().equals("com.rk.carrecorder.CameraActivity")) {
                    Log.d(TAG, "reverse on to send broadcast");
                    sendBroadcast(new Intent("android.intent.action.REVERSE_ON"));
                } else {
                    Log.d(TAG, "reverse on to start activity");
                    startActivity(mIntent);
                }
            } catch(ActivityNotFoundException e) {
                e.printStackTrace();
            }
        } else if (state.equals("over")) {
            sendBroadcast(new Intent("android.intent.action.REVERSE_OVER"));
            //mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
        }
    }
}
